package com.coocaa.ops.admin.v1.upload.util;

import org.apache.commons.codec.binary.Hex;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author bijiahao
 * @date : 2019/2/15.
 * @description
 */
public class FileMd5Util {

    public static String getFileMD5(String inputFile) {
        return getFileMD5(new File(inputFile));
    }

    public static String getHttpPicUrlMd5(String picUrl) {
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        BufferedInputStream bis = null;
        FileOutputStream out = null;
        try {
            // 建立链接
            URL url = new URL(picUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            inputStream = conn.getInputStream();
            int bufferSize = 256 * 1024;
            bis = new BufferedInputStream(inputStream);
            byte[] buffer = new byte[bufferSize];
            // 拿到一个MD5转换器（同样，这里可以换成SHA1）
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            int length;
            // 使用DigestInputStream
            while ((length = bis.read(buffer)) != -1) {
                // 更新
                messageDigest.update(buffer, 0, length);
            }
            // 拿到结果，也是字节数组，包含16个元素
            byte[] resultByteArray = messageDigest.digest();
            byte b[] = new byte[1024];
            int len = 0;
            while ((len = bis.read(b)) != -1) {
                out.write(b, 0, len);
            }
            // 同样，把字节数组转换成字符串
            return Hex.encodeHexString(resultByteArray);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (bis != null) {
                    bis.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

    public static String getFileMD5(File inputFile) {
        // 缓冲区大小（这个可以抽出一个参数）
        int bufferSize = 256 * 1024;
        FileInputStream fileInputStream = null;
        try {
            // 拿到一个MD5转换器（同样，这里可以换成SHA1）
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            // 使用DigestInputStream
            fileInputStream = new FileInputStream(inputFile);
            // read的过程中进行MD5处理，直到读完文件
            byte[] buffer = new byte[bufferSize];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
                // 更新
                messageDigest.update(buffer, 0, length);
            }
            // 拿到结果，也是字节数组，包含16个元素
            byte[] resultByteArray = messageDigest.digest();
            // 同样，把字节数组转换成字符串
            return Hex.encodeHexString(resultByteArray);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) throws Exception {
        String file = "/Users/bijiahao/Downloads/20190218151256472955.apk";
        long start = System.currentTimeMillis();
        System.out.println(getFileMD5(file));
        long end = System.currentTimeMillis();
        System.out.println("====Time consuming " + (end - start));
        // 运营图推荐位md5验证
        String url = "http://art.51arttouch.com/upload/201905/20/D29E6F7DE5017CEB5377676AA02B304F.jpg";
        long startTime = System.currentTimeMillis();
        System.out.println(getHttpPicUrlMd5(url));
        long endTime = System.currentTimeMillis();
        System.out.println("====Time consuming " + (endTime - startTime));


    }

}
